package sk.isomi.helpers;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import sk.isomi.enums.Gender;
import sk.isomi.exceptions.ArgumentException;

public class DateHelper {

	/**
	 * Parse BirtNumber to Date
	 * @param birtNumber 
	 * @return
	 */
	public static Date parseBirthNumber(String birtNumber) {
		if (birtNumber == null || ! birtNumber.matches("^\\d{6}/\\d{3,4}$")) {
			throw new ArgumentException("Parsing error", "BirthNumber", birtNumber);			
		}
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, getBirtYear(birtNumber));
		calendar.set(Calendar.MONTH, getBirtMonth(birtNumber) - 1);
		calendar.set(Calendar.DAY_OF_MONTH, getBirtDay(birtNumber));
				
		return calendar.getTime();
	}
	
	public static String formatDate(Date date, String pattern) {
		SimpleDateFormat sdf;
		try {
			sdf = new SimpleDateFormat(pattern);
		} catch (IllegalArgumentException e) {
			sdf = new SimpleDateFormat("yy/MM/dd");
			//TODO log warning
		}
		return sdf.format(date);
	}
	
	private static int getBirtDay(String dateNumber) {
		return Integer.parseInt(dateNumber.substring(4, 6)); 
	}

	private static int getBirtMonth(String dateNumber) {
		int month = Integer.parseInt(dateNumber.substring(2, 4));
		if (month > 12) {
			month -= 50;
		}
		return month; 
	}
	
	private static int  getBirtYear(String dateNumber) {
		return Integer.parseInt(dateNumber.substring(0, 2)) + 1900; //FIXME nerieseny problem s narodenymi po roku 2000 
	}

	public static int calcAge(Date dateOfBirt) {	
		Calendar calDoB = Calendar.getInstance();
		int actualYear = calDoB.get(Calendar.YEAR);		
		calDoB.setTime(dateOfBirt);
		int dobYear = calDoB.get(Calendar.YEAR);
				
		return actualYear - dobYear;
	}

	public static int diffDateDays(Date date1, Date date2) {
	    long diff = date2.getTime() - date1.getTime();

	    return (int) Math.abs((diff / (1000 * 60 * 60 * 24)));		
	}
	
	public static Gender parseGender(String birtNumber) {
		if (birtNumber == null || ! birtNumber.matches("^\\d{6}/\\d{3,4}$")) {
			throw new ArgumentException("Parsing error (try to get gender)", "birtNumber", birtNumber);
		}
		 		
		return (Integer.parseInt(birtNumber.substring(2, 3)) > 1) ? Gender.FEMALE : Gender.MALE;
	}	

//	public static void main(String[] args) {
//		Date test = parseBirtNumber("8012071111");
//		System.out.println(test);
//
//		Gender ge = parseGender("8012071111");
//		System.out.println(ge);
//		ge = parseGender("8062071111");
//		System.out.println(ge);
//		Calendar calendar = Calendar.getInstance();
//		calendar.clear();
//		calendar.set(Calendar.YEAR, 1840);
//
//		System.out.println(calendar.getTime());
//		System.out.println(calendar.getTime().getTime());		
//	}
}
